package com.mck.controller;

import com.mck.entity.Pagination;
import com.mck.entity.Result;
import com.mck.entity.User;
import com.mck.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Slf4j
@RequestMapping("/api/public/users") // 添加前缀
@RestController
public class UserController {

    @Autowired
    private UserService userService;  // 方法注入

    /**
     * 获取全部用户
     */
    // @RequestMapping(value = "/users", method = RequestMethod.GET)
    @GetMapping
    public Result findAllUser(@RequestParam(defaultValue = "1") Integer currentPage, @RequestParam(defaultValue = "10") Integer pageSize) {
        // System.out.println("查询全部用户");
        log.info("查询全部用户");

        Pagination<User> user = userService.findAllUser(currentPage, pageSize);
        return Result.success(user);
    }

    /**
     * 查询用户
     */
    @GetMapping("/specific")
    public Result findUserInfoByUserInfo(@ModelAttribute User user) {  // @RequestParam用于单个参数，@ModelAttribute用于对象参数，将数据绑定到user对象中
        // System.out.println("根据id查询用户");
        log.info("根据条件查询用户: {}", user);
        List<User> userList = userService.findUserInfoByUserInfo(user);
        return Result.success(userList);
    }

    /**
     * 删除指定id的用户
     */
    @DeleteMapping("/{userId}")
    // public Result delete(@RequestParam("id") Integer userId) {   // @RequestParam默认需要参数传递
    // public Result delete(Integer userId) {   // 请求参数与形参一致时，可省略@RequestParam("id")
    public Result deleteUserById(@PathVariable Integer userId) {  // @PathVariable将路径中的参数绑定到形参   URL路径中（/users/{userId}）
        // System.out.println("删除用户");
        log.info("删除用户: {}", userId);

        userService.deleteUserById(userId);
        return Result.success();
    }

    /**
     * 删除用户列表
     */
    @DeleteMapping("/list")
    public Result deleteUserBySpecific(@RequestBody List<User> user) {  // @RequestBody将请求体中的json数据转换为User对象
        log.info("删除用户列表: {}", user);

        userService.deleteUserList(user);
        return Result.success();
    }

    /**
     * 新增用户
     */
    @PostMapping
    public Result addUser(@RequestBody User user) {
        log.info("新增用户: {}", user);

        userService.addUser(user);
        return Result.success();
    }

    /**
     * 添加用户列表
     */
    @PostMapping("/list")
    public Result addUserList(@RequestBody List<User> userList) {  // @RequestBody将请求体中的json数据转换为User对象
        log.info("新增用户列表: {}", userList);

        userService.addUserList(userList);
        return Result.success();
    }

    /**
     * 修改用户
     */
    @PutMapping
    public Result updateUser(@RequestBody User user) {
        // System.out.println(user);
        log.info("修改用户: {}", user);

        userService.updateUser(user);
        return Result.success();
    }
}
